import { Component, Input, OnInit } from '@angular/core';
import { environment } from '@env/environment';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { SystemDictService } from '../../../system/dict/service/service.service';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { NzDrawerRef } from 'ng-zorro-antd/drawer';
import { StationService } from '../service/station.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadFile } from 'ng-zorro-antd/upload';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styles: [],
})
export class StationEditComponent implements OnInit {
  @Input()
  record: any;
  previewVisible = false;
  previewVisible2 = false;
  previewVisible3 = false;
  previewVisible4 = false;
  upload = environment.uploadUrl;
  stationPhoto: NzUploadFile = {
    uid: '-1',
    name: 'image.png',
    status: 'done',
    url: '',
  };
  idCardFront: NzUploadFile = {
    uid: '-1',
    name: 'image.png',
    status: 'done',
    url: '',
  };
  idCardBack: NzUploadFile = {
    uid: '-1',
    name: 'image.png',
    status: 'done',
    url: '',
  };
  personalIdCardPhoto: NzUploadFile = {
    uid: '-1',
    name: 'image.png',
    status: 'done',
    url: '',
  };
  form: FormGroup;
  statList: any;
  stationPhotoPreview: any;
  idCardFrontPreview: any;
  idCardBackPreview: any;
  personalIdCardPhotoPreview: any;
  constructor(
    private stationService: StationService,
    private fb: FormBuilder,
    private modal: NzDrawerRef,
    private dictService: SystemDictService,
    private message: NzMessageService,
  ) {
    this.form = this.fb.group({
      id: [null],
      stationStats: [null, [Validators.required]],
    });
  }

  getBase64(file: File): Promise<string | ArrayBuffer | null> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  }

  handlePreview = async (file: NzUploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj!);
    }
    this.stationPhotoPreview = file.url || file.preview;
  };

  handlePreview2 = async (file: NzUploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj!);
    }
    this.idCardFrontPreview = file.url || file.preview;
  };

  handlePreview3 = async (file: NzUploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj!);
    }
    this.idCardBackPreview = file.url || file.preview;
  };

  handlePreview4 = async (file: NzUploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj!);
    }
    this.personalIdCardPhotoPreview = file.url || file.preview;
  };

  ngOnInit(): void {
    this.form.patchValue(this.record);
    this.stationPhoto['url'] = this.record.stationPhoto;
    this.idCardFront['url'] = this.record.idCardFront;
    this.idCardBack['url'] = this.record.idCardBack;
    this.personalIdCardPhoto['url'] = this.record.personalIdCardPhoto;
    this.handlePreview(this.stationPhoto);
    this.handlePreview2(this.idCardFront);
    this.handlePreview3(this.idCardBack);
    this.handlePreview4(this.personalIdCardPhoto);
    this.dictService.dictList(environment.dict.stationStat).subscribe((res) => {
      this.statList = res.data;
    });
  }

  save() {
    const isValid = this.validate();
    if (!isValid) {
      this.message.create('error', ' 请填写必填内容！');
      return;
    }

    const postData = {
      ...this.form.value,
    };

    this.stationService.submit(postData).subscribe(() => {
      this.close(true);
    });
  }

  close(fg?: boolean) {
    this.modal.close(fg);
  }

  validate() {
    for (const key in this.form.controls) {
      if (this.form.controls.hasOwnProperty(key)) {
        const element = this.form.controls[key];
        element.markAsDirty();
        element.updateValueAndValidity();
      }
    }
    return this.form.valid;
  }
}
